#include "StdAfx.h"
#include "FormTemplate.h"

FormTemplate* FormTemplate::_instance = 0;

FormTemplate* FormTemplate::GetInstance(Outlook::_ApplicationPtr spApp) {
    if (_instance == 0) {
        _instance = new FormTemplate(spApp);
    }
    return _instance;
}


FormTemplate::~FormTemplate(void)
{
}

int FormTemplate::LoadCustomForm(void)
{
	ATLASSERT(m_spApp);
	HRESULT hr;
	
	Outlook::FormDescriptionPtr spCustomFormDescription;

	Outlook::_ContactItemPtr spCustomContactItem;
	CComVariant myFolder(DISP_E_PARAMNOTFOUND, VT_ERROR);
	//_bstr_t nsName(L"MAPI");

	Outlook::_NameSpacePtr spNs = m_spApp->GetNamespace(L"MAPI");
	ATLASSERT(spNs);
	Outlook::MAPIFolderPtr spContactFolder = spNs->GetDefaultFolder(Outlook::olFolderContacts);
	ATLASSERT(spContactFolder);
	spCustomContactItem = m_spApp->CreateItemFromTemplate(L"C:\\Custom.oft",myFolder);
	ATLASSERT(spCustomContactItem);

	/**** publish form in Contacts folder ****/
	spCustomFormDescription = spCustomContactItem->GetFormDescription();
	ATLASSERT(spCustomFormDescription);

	spCustomFormDescription->PutName(L"Custom");
	CComVariant varContactsFolder(spContactFolder);
	//publish the oft to the FolderContacts
	Outlook::OlFormRegistry ofr = Outlook::olFolderRegistry;
	hr = spCustomFormDescription->PublishForm(ofr,varContactsFolder);
	if(FAILED(hr)){
		MessageBox(NULL,L"Publish failed",L"Outlook Addin",MB_ICONERROR);
		return -1;
	}

	/**** Convert existing items ****/
	int changes =0;
	Outlook::_ItemsPtr spItems = spContactFolder->Items;
	long itemCount = spItems->Count;
	Outlook::_ContactItemPtr spNewContactItem;
	for( int i = 1 ; i <= itemCount ; i++ ){
		CComVariant nItem(i);
		Outlook::_ContactItemPtr spContactitem = spItems->Item(nItem);
		if(!spContactitem) continue;

		std::wstring curMsgClassStr(spContactitem->MessageClass.GetBSTR());
		std::wstring oldMsgClassStr(L"IPM.Contact");

		if(curMsgClassStr.compare(oldMsgClassStr) == 0){
			spContactitem->PutMessageClass(L"IPM.Contact.Custom");
			spContactitem->Save();
			spNewContactItem = spContactitem->Copy();
			hr = spContactitem->Delete();
			if(FAILED(hr)){
				MessageBox(NULL,L"Conversion error",L"Outlook Addin",MB_ICONERROR);
				return -1;
			}
			
			else spNewContactItem->Close(Outlook::olSave);
			changes++;
		}
	}

	spCustomContactItem->Close(Outlook::olDiscard);
    MessageBox(NULL,L"Custom form loaded correctly",L"Outlook Addin",MB_ICONINFORMATION);
	return 0;
}

int FormTemplate::LoadDefaultForm(void)
{
	return 0;
}